package com.ysm.smfu.view;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;


public class MyCycleViewPager extends ViewPager {

    private PagerAdapter adapter;
    private int maxHeight = 600;

    public MyCycleViewPager(Context context) {
        super(context);
    }

    public MyCycleViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public void setAdapter(PagerAdapter adapter) {
        this.adapter = adapter;
        // 包装
//        InnerAdapter innerAdapter = new InnerAdapter(adapter);
        //使用包装过的adapter
        super.setAdapter(adapter);
        setCurrentItem(0);
        startScroll();
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                //手指按下停止轮播
                stopScroll();
                break;
            case MotionEvent.ACTION_CANCEL://手指事件取消  从外边抬起的时候取消事件
            case MotionEvent.ACTION_UP:
                startScroll();
                break;
        }
        return super.onTouchEvent(ev);
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int currentItem = getCurrentItem();
            currentItem++;
            setCurrentItem(currentItem);
            handler.sendEmptyMessageDelayed(1, 2000);
        }
    };

    public void startScroll() {
        //启动轮播
        if (adapter.getCount() > 1)
            handler.sendEmptyMessageDelayed(1, 2000);
    }

    /**
     * 停止轮播
     */
    public void stopScroll() {
        handler.removeMessages(1);
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        stopScroll();
    }

//    @Override
//    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//
//        int height = 0;
//        //下面遍历所有child的高度
//        for (int i = 0; i < getChildCount(); i++) {
//            View child = getChildAt(i);
//            child.measure(widthMeasureSpec,
//                    MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
//            int h = child.getMeasuredHeight();
//            if (h > height) //采用最大的view的高度。
//                height = h;
//        }
//        if (height > maxHeight)
//            height = maxHeight;
//        heightMeasureSpec = MeasureSpec.makeMeasureSpec(height,
//                MeasureSpec.EXACTLY);
//        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
//    }
}
